<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Post\ImportPatentPost;
use App\Admin\Actions\Post\TransactionPost;
use App\Extensions\Tools\PatentMonitorBatch;
use App\Patent;
use App\Repositories\PatentRepository;
use App\Services\PatentService;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Grid\Tools;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\DB;

class PatentLibraryController extends AdminController
{
    protected $title = '本校专利库';
    public $repository;
    public $service;

    public function __construct(PatentRepository $repository, PatentService $service)
    {
        $this->repository = $repository;
        $this->service = $service;
    }

    public function index(Content $content)
    {
        $grid = $this->repository->adminGrid('apply_date');
        $grid->header(function () {
            $data = Patent::query()
                ->select(DB::raw('count(*) as count,patent_type_id'))
                ->groupBy(['patent_type_id'])->get()->map(function ($item) {
                    return [
                        'name' => data_get(patent_type_select_option(), $item['patent_type_id']),
                        'value' => $item['count']
                    ];
                })->pluck('value', 'name')->toArray();
            return view('admin.statistics.common-table-header', compact('data'));
        });
        $grid = $this->service->gridColumn($grid);
        $grid->tools(function(Tools $tools){
            $tools->append(new ImportPatentPost());
            $tools->append(new PatentMonitorBatch());
        });
        $grid->disableCreateButton(false);
        $grid->actions(function(Actions $actions){
            $actions->disableView();
            $row = $actions->row;
            if ($row->state == 1) {
                $actions->prepend(new  TransactionPost($actions));
            }
        });
        return $content->title('专利库')->body($grid);
    }

    protected function form()
    {
        return $this->service->form($this->repository->form());
    }
}
